﻿using Microsoft.AspNetCore.Mvc.ApplicationModels;
using System.Text.RegularExpressions;

namespace VueShopApi.Common
{

    public class GroupNameVersionRoutingConvention : IApplicationModelConvention
    {
        private readonly string _routePrefix;
        public GroupNameVersionRoutingConvention(string routePrefix = "")
        {
            _routePrefix = routePrefix;
        }

        public void Apply(ApplicationModel application)
        {
            foreach (var controller in application.Controllers)
            {
                var routeAttribute = controller.Selectors.FirstOrDefault()?.AttributeRouteModel;
                //如果 Controller 没有标记 [Route]，则跳过版本路由规则
                if (routeAttribute == null)
                    continue;

                var version = controller.ApiExplorer.GroupName;
                //如果 Controller 没有标记 [ApiExplorer]，则跳过版本路由规则 
                if (string.IsNullOrEmpty(version))
                    continue;

                //如果 GroupName 不符合版本号的定义，则跳过版本路由规则
                if (!Regex.IsMatch(version, @"^v(\d+)$"))
                    continue;

                string template = routeAttribute.Template.Replace("api", $"api/{_routePrefix}/{version}");
                controller.Selectors[0].AttributeRouteModel = new AttributeRouteModel()
                {
                    Template = template
                };
            }
        }
    }
}
